import os
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
from queue import Queue
from image_extractor import extract_images_from_file
from utils.thread_pool import ThreadPool


class ImageExtractorApp:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("文档图片提取器")
        self.root.configure(bg="#f0f0f0")  # 设置背景颜色
        self.center_window()
        self.create_widgets()
        self.thread_pool = ThreadPool(max_workers=5)
        self.log_queue = Queue()
        self.files = []
        self.total_files = 0
        self.processed_files = 0

    def center_window(self):
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        window_width = 600
        window_height = 390
        x = (screen_width // 2) - (window_width // 2)
        y = (screen_height // 2) - (window_height // 2) - 100
        self.root.geometry(f"{window_width}x{window_height}+{x}+{y}")

    def create_widgets(self):
        # 增加字体大小
        font_size = 12  # 字体大小

        # 使用ttk样式来使界面看起来更现代
        style = ttk.Style()
        style.configure(
            "TButton", padding=10, relief="flat", font=("TkDefaultFont", font_size)
        )
        style.configure("TLabel", padding=10, font=("TkDefaultFont", font_size))

        # 日志部分
        log_frame = ttk.LabelFrame(
            self.root, text="日志", padding=10, style="TLabelframe"
        )
        log_frame.pack(fill=tk.BOTH, expand=True)

        self.log_text = tk.Text(
            log_frame,
            height=10,
            bg="#ffffff",
            fg="#333333",
            wrap="word",
            font=("TkDefaultFont", font_size),  # 文本区域字体大小
        )
        self.log_text.pack(fill=tk.BOTH, expand=True)

        # 进度条部分
        self.status_label = ttk.Label(
            self.root, text="请选择文件后提取", style="TLabel"
        )
        self.status_label.pack(pady=5)

        self.progress_bar = ttk.Progressbar(
            self.root,
            orient="horizontal",
            length=300,
            mode="determinate",
            style="TProgressbar",
        )
        self.progress_bar.pack(pady=(5, 0))

        # 按钮部分
        frame_buttons = ttk.Frame(self.root, padding=10)
        frame_buttons.pack(fill=tk.X, expand=True, pady=(10, 0))

        self.select_button = ttk.Button(
            frame_buttons, text="选择文件", command=self.select_files, style="TButton"
        )
        self.select_button.pack(side=tk.LEFT, padx=5, pady=0)

        self.extract_button = ttk.Button(
            frame_buttons,
            text="开始提取",
            command=self.start_extraction,
            style="TButton",
        )
        self.extract_button.pack(side=tk.LEFT, padx=5, pady=0)

        # 版权信息部分
        copyright_frame = ttk.Frame(self.root, padding=0)
        copyright_frame.pack(side=tk.BOTTOM, fill=tk.X)

        self.copyright_label = ttk.Label(
            copyright_frame,
            text="© 2024 @guominzhi. All rights reserved.",
            style="TLabel",
        )
        self.copyright_label.pack(side=tk.RIGHT)
        self.update_log("欢迎使用文档图片提取器！\n\n")

    def select_files(self):
        files = filedialog.askopenfilenames(
            title="选择文件",
            filetypes=[
                ("支持的文件类型", "*.pdf *.doc *.docx *.xls *.xlsx *.ppt *.pptx")
            ],
        )
        if files:
            self.files = files
            self.total_files = len(files)
            self.processed_files = 0
            self.progress_bar["maximum"] = self.total_files
            self.progress_bar["value"] = 0
            self.status_label.config(text=f"已选择 {self.total_files} 个文件")

    def start_extraction(self):
        if not self.files:
            messagebox.showwarning("警告", "请选择文件后再进行提取！")
            return

        for file in self.files:
            self.thread_pool.submit(self.threaded_extract, file)

    def threaded_extract(self, file_path):
        try:
            extract_images_from_file(file_path)
            self.log_queue.put(
                f"{file_path} 图片提取完成。\n输出文件路径在：{os.path.splitext(file_path)[0] + '_images'}\n\n"
            )
        except Exception as e:
            self.log_queue.put(f"提取失败: {str(e)}\n")

        self.processed_files += 1
        self.progress_bar["value"] = self.processed_files
        if self.processed_files == self.total_files:
            self.log_queue.put("所有文件提取完成。\n")

        self.root.after(100, self.update_ui)

    def update_ui(self):
        while not self.log_queue.empty():
            message = self.log_queue.get()
            self.update_log(message)
        if self.processed_files < self.total_files:
            self.root.after(100, self.update_ui)

    def update_log(self, message):
        if self.log_text is not None:
            self.log_text.insert(tk.END, message)
            self.log_text.see(tk.END)

    def run(self):
        self.root.mainloop()


if __name__ == "__main__":
    app = ImageExtractorApp()
    app.run()
